package cn.com.surker.production.service.impl;

import cn.com.surker.base.pump.dao.PumpNormDao;
import cn.com.surker.base.pump.dao.PumpTypeDao;
import cn.com.surker.base.pump.entity.PumpNorm;
import cn.com.surker.base.pump.entity.PumpType;
import cn.com.surker.common.MessageCenterException;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.oa.dao.OaProductionContractDao;
import cn.com.surker.oa.vo.ProductionContractVo;
import cn.com.surker.production.entity.ProductionPumpPrice;
import cn.com.surker.production.dao.ProductionPumpPriceDao;
import cn.com.surker.production.service.PumpPriceService;
import cn.com.surker.system.dao.SysMessageRecordDao;
import cn.com.surker.system.dao.SysUserPositionDao;
import cn.com.surker.system.entity.SysMessageRecord;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import cn.com.surker.wechat.WechatOaGroupApi;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.com.surker.spring.RestResultDto;

import javax.annotation.Resource;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
* <p>
    * 生产泵送单价表 服务实现类
    * </p>
*
* @author admin
* @since 2024-12-05
*/
public abstract class PumpPriceServiceImpl extends ServiceImpl<ProductionPumpPriceDao, ProductionPumpPrice> implements PumpPriceService {

    @Resource
    protected ProductionPumpPriceDao pumpPriceDao;
    @Resource
    protected OaProductionContractDao productionContractDao;
    @Resource
    protected SysMessageRecordDao messageRecordDao;
    @Resource
    protected SysUserPositionDao userPositionDao;
    @Resource
    protected PumpTypeDao pumpTypeDao;
    @Resource
    protected PumpNormDao pumpNormDao;

    /**
     * 查询生产合同泵送单价信息
     * @param contractId
     * @return
     */
    public Map<String, List<ProductionPumpPrice>> findByContract(Long contractId) {
        if (StringUtils.isNull(contractId))
            return null;
        QueryWrapper<ProductionPumpPrice> query = new QueryWrapper<>();
        query.eq("status", 0);
        query.eq("contract_id", contractId);
        query.orderByDesc("take_time");
        List<ProductionPumpPrice> priceList = pumpPriceDao.selectList(query);
        if (priceList == null || priceList.size() == 0)
            return null;
        Map<String, List<ProductionPumpPrice>> map = new LinkedHashMap<>();
        for (int i = 0; i < priceList.size(); i++) {
            ProductionPumpPrice price = priceList.get(i);
            String takeTime = DateUtil.convertString(price.getTakeTime());
            if (map.containsKey(takeTime)) {
                List<ProductionPumpPrice> tempList = map.get(takeTime);
                tempList.add(price);
                map.put(takeTime, tempList);
            } else {
                List<ProductionPumpPrice> tempList = new ArrayList<>();
                tempList.add(price);
                map.put(takeTime, tempList);
            }
        }
        return map;
    }

    /**
     * 新增生产合同泵送单价信息
     * @return
     */
    public RestResultDto savePrice(ProductionPumpPrice pumpPrice) {
        if (pumpPrice == null)
            throw new MessageCenterException("参数错误");
        if (StringUtils.isNull(pumpPrice.getOrgId()))
            throw new MessageCenterException("合同公司信息为空");
        if (StringUtils.isNull(pumpPrice.getContractId()))
            throw new MessageCenterException("合同信息为空");
        if (StringUtils.isNull(pumpPrice.getSupplierId()))
            throw new MessageCenterException("泵送商信息为空");
        if (StringUtils.isNull(pumpPrice.getPumpType()))
            throw new MessageCenterException("泵送类型为空");
        if (StringUtils.isNull(pumpPrice.getPumpNorms()))
            throw new MessageCenterException("泵送规格为空");
        if (StringUtils.isNull(pumpPrice.getPrice()))
            throw new MessageCenterException("运输单价为空");
        if (StringUtils.isNull(pumpPrice.getTakeTime()))
            throw new MessageCenterException("生效时间为空");

        Date nowDate = new Date();
        ProductionContractVo contract = productionContractDao.selectByIdVo(pumpPrice.getContractId());
        if (contract == null || contract.getStatus().intValue() == 1)
            throw new MessageCenterException("运输合同不存在或已被删除");
//        ProductionTransportPrice transportPrice = new ProductionTransportPrice(orgId, contractId, supplierId, takeDate,
//                transportType, countType, carModel, isSpeed, isLimit, minDistance, maxDistance, minStere, maxStere,price);
        pumpPrice.setCreateTime(nowDate);
//        transportPrice.setCreator(creator);
//        transportPrice.setRemark(remark);
//        transportPrice.setStatus(0);
        ProductionPumpPrice tempPumpPrice = pumpPriceDao.findTakePrice(pumpPrice);
        if (tempPumpPrice != null) {
            ProductionPumpPrice oldPumpPrice = tempPumpPrice;
            tempPumpPrice.setUpdateTime(nowDate);
            tempPumpPrice.setUpdator(pumpPrice.getCreator());
            tempPumpPrice.setPrice(pumpPrice.getPrice());
            tempPumpPrice.setTakeTime(pumpPrice.getTakeTime());
            Integer code = pumpPriceDao.updateById(tempPumpPrice);
            if (code > 0) {
                try {
                    sendMessage(contract, oldPumpPrice, tempPumpPrice, 1);
                } catch (Exception e) {
                    log.error("推送消息异常");
                }
                return RestResultDto.success("保存生产泵送单价成功");
            }
            return RestResultDto.fail("保存泵送单价异常", tempPumpPrice);
        }
        Integer code = pumpPriceDao.insert(pumpPrice);
        if (code > 0) {
            try {
                sendMessage(contract, null, pumpPrice, 0);
            } catch (Exception e) {
                log.error("推送泵送单价新增消息异常");
            }
            return RestResultDto.success("保存成功");
        }
        return RestResultDto.fail("保存泵送单价异常");
    }
    /**
     * 修改泵送单价信息
     * @return
     */
    public RestResultDto updatePrice(ProductionPumpPrice newPumpPrice) {
        if (newPumpPrice == null || StringUtils.isNull(newPumpPrice.getId()))
            throw new MessageCenterException("参数错误");
        ProductionPumpPrice pumpPrice = pumpPriceDao.selectById(newPumpPrice.getId());
        if (pumpPrice == null || pumpPrice.getStatus() == 1)
            throw new MessageCenterException("生产泵送单价不存在或该单价已被禁用");
//        ProductionTransportPrice newTransportPrice = new ProductionTransportPrice(transportPrice.getOrgId(), transportPrice.getContractId(),
//                transportPrice.getSupplierId(), transportPrice.getTakeTime(), transportType, countType, carModel,
//                isSpeed, isLimit, minDistance, maxDistance, minStere, maxStere,price);
        ProductionPumpPrice oldPumpPrice = pumpPrice;
        if (!StringUtils.isNull(newPumpPrice.getPumpType()))
            pumpPrice.setPumpType(newPumpPrice.getPumpType());
        if (!StringUtils.isNull(newPumpPrice.getPumpNorms()))
            pumpPrice.setPumpNorms(newPumpPrice.getPumpNorms());
        if (!StringUtils.isNull(newPumpPrice.getPrice()))
            pumpPrice.setPrice(newPumpPrice.getPrice());
        if (!StringUtils.isNull(newPumpPrice.getTakeTime())) {
            pumpPrice.setTakeTime(newPumpPrice.getTakeTime());
        }
        Date nowDate = new Date();
        pumpPrice.setUpdator(newPumpPrice.getUpdator());
        pumpPrice.setUpdateTime(nowDate);
        Integer code = pumpPriceDao.updateById(pumpPrice);
        if (code > 0) {
            try {
                ProductionContractVo contract = productionContractDao.selectByIdVo(pumpPrice.getContractId());
                sendMessage(contract, oldPumpPrice, newPumpPrice, 1);
            } catch (Exception e) {
                log.error("修改泵送单价推送消息异常");
            }
            return RestResultDto.success("更新成功", pumpPrice);
        }
        return RestResultDto.fail("更新运输单价异常");
    }

    /**
     * 禁用合同
     * @param id
     * @param status
     * @return
     */
    public RestResultDto updateStatus(Long id, Integer status, String creator) {
        if (StringUtils.isAllParamNull(id, status))
            throw new MessageCenterException("参数错误");
        ProductionPumpPrice transportPrice = pumpPriceDao.selectById(id);
        if (transportPrice == null)
            throw new MessageCenterException("泵送单价不存在");
        transportPrice.setStatus(status);
        transportPrice.setUpdateTime(new Date());
        transportPrice.setUpdator(creator);
        Integer code = pumpPriceDao.updateById(transportPrice);
        if (code > 0) {
            return RestResultDto.success("更新成功", transportPrice);
        }
        return RestResultDto.fail("更新运输单价异常");
    }

	@Override
	public Double findByContractV2(Long orgId, Long pumpConId, Long pumpTypeId, Long pumpNormId, String pumpTime) {
		if (pumpConId == null || StringUtils.isBlank(pumpTime) || (pumpTypeId == null && pumpNormId == null)) {
			return null;
		}
		QueryWrapper<ProductionPumpPrice> qw = new QueryWrapper<>();
		qw.eq("status", StateEnum.ENABLED.getCode());
		qw.eq("org_id", orgId);
		qw.eq("contract_id", pumpConId);
		if (pumpTypeId != null) {
			qw.eq("pump_type", pumpTypeId);
		}
		if (pumpNormId != null) {
			qw.eq("pump_norms", pumpNormId);
		}
		qw.le("take_time", pumpTime);
		qw.orderByDesc("take_time");
		qw.last("limit 1");
		ProductionPumpPrice productionPumpPrice = pumpPriceDao.selectOne(qw);
		if (productionPumpPrice != null) {
			Double price = productionPumpPrice.getPrice();
			return price;
		}
		return null;
	}

	/**
     * 消息推送
     * @param contract
     * @param oldPumpPrice
     * @param newPumpPrice
     * @param updateType
     */
    private void sendMessage(ProductionContractVo contract, ProductionPumpPrice oldPumpPrice,
                             ProductionPumpPrice newPumpPrice, Integer updateType) {
        String touser = "lucky|1lt1556|";
        String toname = "万强|罗涛|";
        String message = "";
        Date nowDate = new Date();
        String title = "";//推送标题
        String orgName = "";
        QueryWrapper<PumpType> query = new QueryWrapper<>();
        query.eq("status", 0);
        List<PumpType> typeList = pumpTypeDao.selectList(query);
        QueryWrapper<PumpNorm> normQuery = new QueryWrapper<>();
        query.eq("status", 0);
        List<PumpNorm> normsList = pumpNormDao.selectList(normQuery);
        Map<Long, String> typeMap = new HashMap<>();
        Map<Long, String> normsMap = new HashMap<>();
        if (typeList != null && typeList.size() > 0) {
            for (int i = 0; i < typeList.size(); i++) {
                PumpType pumpType = typeList.get(i);
                typeMap.put(pumpType.getId(), pumpType.getName());
            }
        }
        if (normsList != null && normsList.size() > 0) {
            for (int i = 0; i < normsList.size(); i++) {
                PumpNorm pumpNorm = normsList.get(i);
                normsMap.put(pumpNorm.getId(), pumpNorm.getName());
            }
        }

        if (!StringUtils.isNull(contract.getOrgName()))
            orgName = contract.getOrgName();
        if (updateType == 0) {
            message = "【泵送合同单价新增通知】 " + orgName + " 编号:" + contract.getCode();
            message += "\n泵送合同名称:" + contract.getName();
            if (!StringUtils.isNull(contract.getSupplierName()))
                message += "\n供应商:" + contract.getName();
            if (!StringUtils.isNull(newPumpPrice.getPumpType()) && !StringUtils.isNull(typeMap.get(newPumpPrice.getPumpType())))
                message += "\n泵送类型:" + typeMap.get(newPumpPrice.getPumpType());
            if (!StringUtils.isNull(newPumpPrice.getPumpNorms()) && !StringUtils.isNull(normsMap.get(newPumpPrice.getPumpNorms())))
                message += "\n泵送规格:" + normsMap.get(newPumpPrice.getPumpNorms());
            if (!StringUtils.isNull(newPumpPrice.getTakeTime()))
                message += "\n生效时间:" + DateUtil.convertString(newPumpPrice.getTakeTime());
            message += "\n单价:" + newPumpPrice.getPrice() + "元。";
            if (!StringUtils.isNull(newPumpPrice.getCreator()))
                message += "\n操作人:" + newPumpPrice.getCreator();
            if (!StringUtils.isNull(newPumpPrice.getRemark()))
                message += "\n备注:" + newPumpPrice.getRemark();
            message += "\n操作时间:" + DateUtil.convertString(nowDate);
        } else if (updateType == 1){
            message = "【泵送合同单价变更通知】 " + orgName + " 编号:" + contract.getCode();
            message += "\n泵送合同名称:" + contract.getName();
            if (!StringUtils.isNull(contract.getSupplierName()))
                message += "\n供应商:" + contract.getName();
            if (!StringUtils.isNull(newPumpPrice.getPumpType()) && !StringUtils.isNull(oldPumpPrice.getPumpType())
                    && !StringUtils.isNull(typeMap.get(newPumpPrice.getPumpType()))&& !StringUtils.isNull(typeMap.get(oldPumpPrice.getPumpType()))) {
                message += "\n泵送类型:" + typeMap.get(newPumpPrice.getPumpType()) + "-->" + typeMap.get(newPumpPrice.getPumpType());
            }
            if (!StringUtils.isNull(newPumpPrice.getPumpNorms()) && !StringUtils.isNull(oldPumpPrice.getPumpNorms())
                    && !StringUtils.isNull(normsMap.get(newPumpPrice.getPumpNorms()))&& !StringUtils.isNull(normsMap.get(oldPumpPrice.getPumpNorms()))) {
                message += "\n泵送规格:" + normsMap.get(newPumpPrice.getPumpNorms()) + "-->" + normsMap.get(newPumpPrice.getPumpNorms());
            }
            if (!StringUtils.isNull(newPumpPrice.getTakeTime()) && !StringUtils.isNull(oldPumpPrice.getTakeTime())) {
                String oldTakeTime = DateUtil.convertString(oldPumpPrice.getTakeTime());
                String newTakeTime = DateUtil.convertString(newPumpPrice.getTakeTime());
                if (!oldPumpPrice.equals(newTakeTime))
                    message += "\n生效时间:" + oldTakeTime + "-->" + newTakeTime;
            }
            if (!StringUtils.isNull(newPumpPrice.getPrice()) && !StringUtils.isNull(oldPumpPrice.getPrice()))
                message += "\n单价:" + oldPumpPrice.getPrice() + "-->" + newPumpPrice.getPrice() + "元。";
            if (!StringUtils.isNull(newPumpPrice.getCreator()))
                message += "\n操作人:" + newPumpPrice.getCreator();
            if (!StringUtils.isNull(newPumpPrice.getRemark()))
                message += "\n备注:" + newPumpPrice.getRemark();
            message += "\n操作时间:" + DateUtil.convertString(nowDate);
        }

        List<Map<String, Object>> list = userPositionDao.hasGeneralManager(contract.getOrgId(), "财务统计", "统计");
        List<Map<String, Object>> list1 = userPositionDao.hasGeneralManager(contract.getOrgId(), "生产内业", "生产统计");
        List<Map<String, Object>> list2 = userPositionDao.hasGeneralManager(contract.getOrgId(), "生产副总", "生产经理");
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> temp = list.get(i);
                String name = StringUtils.convertString(temp.get("name"));
                if (!StringUtils.isNull(name) && toname.indexOf(name) == -1) {
                    toname += temp.get("name") + "|";
                    touser += temp.get("username") + "|";
                }
            }
        }
        if (list1 != null && list1.size() > 0) {
            for (int i = 0; i < list1.size(); i++) {
                Map<String, Object> temp = list1.get(i);
                String name = StringUtils.convertString(temp.get("name"));
                if (!StringUtils.isNull(name) && toname.indexOf(name) == -1) {
                    toname += temp.get("name") + "|";
                    touser += temp.get("username") + "|";
                }
            }
        }
        if (list2 != null && list2.size() > 0) {
            for (int i = 0; i < list2.size(); i++) {
                Map<String, Object> temp = list2.get(i);
                String name = StringUtils.convertString(temp.get("name"));
                if (!StringUtils.isNull(name) && toname.indexOf(name) == -1) {
                    toname += temp.get("name") + "|";
                    touser += temp.get("username") + "|";
                }
            }
        }

        toname = toname.substring(0, toname.length() - 1);
        touser = touser.substring(0, touser.length() - 1);
        SysMessageRecord record = new SysMessageRecord(touser, toname, "", WechatOaGroupApi.corpID, "", contract.getOrgId(),
                "", 1, 1, title, "",
                message, "", 1, 0, "", "", nowDate);
        messageRecordDao.insert(record);
        WechatOaGroupApi.sendTextMessage(WechatOaGroupApi.corpID, WechatOaGroupApi.corpSecret,
                WechatOaGroupApi.agentId, touser, message);

    }
}